/**
 * @description koa-webpack-hot
 *
 */

const webpackHotMW = require('webpack-hot-middleware');

const middleware = function middleware(doIt, req, res) {
    let originalEnd = res.end;

    return function(done) {
        res.end = function() {
            originalEnd.apply(this, arguments);
            done(null, 0);
        };

        doIt(req, res, function() {
            done(null, 1);
        });
    };
};


module.exports = function(compiler, option) {
    const action = webpackHotMW(compiler, option);

    return function *(next) {
        const nextStep = yield middleware(action, this.req, this.res);

        if(nextStep && next) {
            yield next;
        }
    };
};